<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\library\Token;
use app\common\model\Auto;
use app\common\model\card\Entity;
use app\common\model\card\Entitylog;
use app\common\model\card\Kabaw;
use app\common\model\card\Kabawlogtype;
use app\common\model\card\Kabawtype;
use app\common\model\card\Type;
use app\common\model\Member;
use app\common\model\MemberMoneyLog;
use app\common\model\Merchantgoods;
use app\common\model\Mycard;
use app\common\model\Mycardlog;
use app\common\model\Order;
use app\common\model\Refund;
use app\common\model\Regionserviceuser;
use app\common\model\Washlog;
use Exception;
use fast\Random;
use think\Db;
use think\Log;
use think\Validate;

/**
 * 用户订单卡券接口
 */
class Myorder extends Api
{
    protected $noNeedLogin = ['notifyx'];
    protected $noNeedRight = ['*'];
    protected $regionserviceUser = [];

    public function _initialize()
    {
        parent::_initialize();
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token = Token::get($token);
        //if ($token["type"] != 0) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
        /*判断当前账号身份 end*/
        //$this->auth->id=13;
        $user = Member::get($this->auth->id);
        if (empty($user)) $this->error("用户不存在");
    }

    /**
     * 兑换实体卡
     * */
    public function exchange()
    {
        $data = [
            ['exchange_number', 'require', '兑换号码不能为空'],
            ['code', 'require', '兑换密码不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        if(strlen($param["exchange_number"])!=9) $this->error("请输入正确的兑换号码");
        $log = Entitylog::where(["exchange_number" => $param["exchange_number"], "code" => $param["code"]])->find();
        if (empty($log)) $this->error("请检查兑换号码和兑换密码");
        if ($log["status"] == 1) $this->error("该号码已兑换");
        if ($log["status"] == 2) $this->error("该号码已失效");
        if(!empty($log["exchange_start_time"]) && $log["exchange_start_time"] > time()) $this->error("未到兑换时间");
        if ($log["card_dealer_id"]>0 && $log["exchange_start_time"] < time() && $log["exchange_end_time"] < time()) {
            $log->save([
                "status" => '2'
            ]);
            $this->error("已失效");
        }
        $time = time();
        Db::startTrans();
        try {
            $ret = $log->save([
                "member_id" => $this->auth->id,
                "status" => '1',
                "exchange_time" => $time,
            ]);
            $card_entity = Entity::get($log["card_entity_id"]);
            $model = new Mycardlog();
            $card_data = [
                "type_data" => '3',
                "order_id" => $card_entity["id"],
                "card_kabaw_id" => $card_entity["card_kabaw_id"],//卡包
                "name" => "实体卡(" . $card_entity["kabaw_name"] . ")",
                "price" => $card_entity["kabaw_all_price"],
                "illustrate" => $card_entity["kabaw_illustrate"],
                "details" => json_encode($log),
                "member_id" => $this->auth->id,
                "start_time" => $time,
                "end_time" => strtotime("+" . $card_entity["kabaw_fate"] . " days", $time),
                "write_number" => $model->write_number(10),
                "createtime" => time(),
            ];
            $mycardModel = new Mycard();
            $mycard_id = $mycardModel->insertGetId($card_data);
            $mycardModel->getCode($mycard_id, $card_data["type_data"]);//获取二维码
            $kabawtype = Kabawlogtype::where(["card_kabaw_id" => $card_entity["card_kabaw_id"],"card_kabaw_entity_id"=>$card_entity["id"]])->select();//实体卡卡包洗车类型
            $cardlog_data = [];
            if (!empty($kabawtype)) {
                foreach ($kabawtype as $k => $v) {
                    $cardlog_data[$k] = [
                        "card_type_name" => $v["card_type_name"],
                        "card_type_id" => $v["card_type_id"],
                        "number" => $v["number"],
                        "residue" => $v["number"],
                        "price" => $v["price"],
                        "all_cost" => $v["all_cost"],
                        "mycard_id" => $mycard_id,
                        "write_number" => $model->write_number(10),
                        "highest_price" => $v["highest_price"],
                    ];
                }
                if (!empty($cardlog_data)) {
                    Mycardlog::insertAll($cardlog_data);
                }
            }
            if(!empty($log["card_dealer_id"])){
                //发送消息
                \app\common\model\Message::create([
                    "title" => "兑换实体卡成功",
                    "member_ids" => $log["card_dealer_id"],
                    "info" => "兑换实体卡成功（编号：" . $log["id"] . "）",
                    "createtime" => time(),
                ]);
            }
            //2023-8-24 新增 绑定卡经销商 start
            if($log["transfer_data"]==1 && !empty($log["card_dealer_id"]))
            {
                $user=Member::where(["id"=>$this->auth->id])->find();
                if(!empty($user) && empty($user["agent_id"]))
                {
                    $user->agent_id=$log["card_dealer_id"];
                    $user->agent_data=2;
                    $user->save();
                }
            }
            //2023-8-24 新增 绑定卡经销商 end
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success("兑换成功");
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 创建订单
     * */
    public function createOrder()
    {
        if (!$this->request->param("id")) $this->error("id为空");
        $type = $this->request->param("type") ?? 0;//类型:0=普通商品,1=卡包,2=店铺洗车卡
        $id = $this->request->param("id");
        $model = new Merchantgoods();
        if (empty($type) || $type == 2) {
            $goods = $model->get($id);
        }
        if ($type == 1) {
            $goods = Kabaw::get($id);
        }
        $orderModel = new \app\common\model\Order();
        if (empty($goods)) $this->error("商品不存在");
        if ($goods["status"] != 1 && (empty($type) || $type == 2)) $this->error("商品状态错误");
        if ($goods["status"] != 0 && $type == 1) $this->error("商品状态错误");
        $params = $this->request->param();
        $out_trade_no = date('ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $order_data = [
            "type_data" => $params["type"],
            "card_kabaw_id" => $goods["id"],
            "name" => $goods["name"],
            "out_trade_no" => $out_trade_no,
            "details" => json_encode($goods),
            "illustrate" => $goods["illustrate"] ?? '',
            "order_no" => Random::numeric(10),
            "member_id" => $this->auth->id,
            "createtime" => time(),
            "price" => $goods["price"]??$goods["all_price"],
        ];
        if (empty($type) || $type == 2) {
            $order_data["merchant_id"] = $goods["merchant_id"];
            $order_data["illustrate"] = $goods["refer"];
            $merchant = \app\common\model\Merchant::field("classify")
                ->where(["id" => $goods["merchant_id"]])->find();
            $actual_payment = $model->actual_payment($goods["price"], $merchant["classify"]);
            $order_data["actual_payment"] = $actual_payment["actual_payment"] ?? $goods["price"];
            $order_data["discount"] = $actual_payment["discount"]??0;//优惠金额
            $order_data["platform_money"] = $actual_payment["platform"]??0;//平台抽成
            $order_data["commission"] = $actual_payment?json_encode($actual_payment):'';//平台抽成
            $merchant_money=bcsub($actual_payment["price"],$actual_payment["platform"],2);
            $order_data["merchantuser_money"] = $actual_payment["platform"]?$merchant_money:$actual_payment["price"];//店铺收益
            //$order_data["price"] = $goods["price"];
        } else {
            $order_data["price"] = $goods["all_price"];
            $order_data["actual_payment"] = $order_data["price"];
        }
        $user = $this->auth->getUser();
        $data=[];
        Db::startTrans();
        //$order_data["price"]=0.01;
        try {
            $orde_id = $orderModel->insertGetId($order_data);
            //$user["openid"] = 'oTE855GNkbphAjBdB3fu6v5UvPiE';
            if($order_data["price"]>0){
                $data = Service::submitOrder($order_data["actual_payment"], $out_trade_no, "wechat", $goods["name"]??"购买",
                    $this->request->domain() . '/api/index/notifyx/paytype/wechat',
                    $this->request->domain() . '/api/index/notifyx/paytype/wechat',
                    "miniapp", $user["openid"]);
            }
            Db::commit();
            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            Db::rollback();
        }
        if($order_data["price"]>0){
            $this->success('成功', ["id" => $orde_id, 'data' => $data,"wxpay"=>true]);
        }else{
            $this->success('成功', ["id" => $orde_id,"wxpay"=>false]);
        }
    }


    /**
     * 我的卡券
     * */
    public function cardList()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $status = !$this->request->param('status') ? 0 : $this->request->param('status');//状态:0=待使用,1=已过期
        $where = ["member_id" => $this->auth->id, "status" => $status];
        $list = Mycard::field("id,name,price,illustrate,from_unixtime(start_time, '%Y-%m-%d %H:%i:%s') start_time,
        from_unixtime(end_time, '%Y-%m-%d %H:%i:%s') end_time,status,type_data,merchant_goods_id,code")
            ->where($where)
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v) {
                $log = Mycardlog::field("card_type_name,card_type_id,number,residue")->where(["mycard_id" => $v["id"]])->select();
                $v["log"] = $log;
            });
        $this->success("成功", $list);
    }

    /**
     * 我的订单
     * */
    public function orderList()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $type_data = $this->request->param('type_data');//类型:0=普通商品,1=卡包,2=店铺洗车卡
        $where = ["type_data" => $this->request->param('type_data')];
        $status_where= "1=1";
        if ($type_data == 2) {
            $where = "type_data ='0' or type_data='2'";
        }
        if($this->request->param('status') && $this->request->param('status')==1){
            //$status_where=" status <> '2'";
            if($type_data==2){
                $status_where=" status ='1' or status='3'";

            }else{
                $status_where=" status ='1' and id in(select order_id from tx_mycard where type_data='1' and status='0')";
            }
        }
        $list = Order::field("id,name,price,status,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime,code,order_no,type_data")
            ->where(["member_id" => $this->auth->id])
            ->where($where)
            ->where($status_where)
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功", $list);
    }

    /**
     * 订单详情
     * */
    public function orderSee()
    {
        if (!$this->request->param("id")) $this->error("id为空");
        $list = Order::field("id,name,price,status,type_data,order_no,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime")->where(["id" => $this->request->param("id")])->find();
        $this->success("成功", $list);
    }

    /**
     * 洗车记录列表
     * */
    public function washlogList()
    {
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list = Washlog::field("id,name,card_type_name,status,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime,image,merchant_name")
            ->where(["member_id" => $this->auth->id])
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功", $list);

    }

    /**
     * 查看评价
     * */
    public function evaluateSee()
    {
        if (!$this->request->param("id")) $this->error("洗车记录id为空");
        $list = Washlog::field("id,score,evaluate,evaluate_images,from_unixtime(evaluate_time, '%Y-%m-%d %H:%i:%s') evaluate_time,status,anonymous")
            ->where(["id" => $this->request->param("id")])
            ->find();
        if (!empty($list) && !empty($list["evaluate_images"])) $list["evaluate_images"] = explode(",", $list["evaluate_images"]);
        $this->success("成功", $list);
    }

    /**
     * 评价
     * */
    public function evaluate()
    {
        $data = [
            ['id', 'require', '洗车记录id不能为空'],
            ['score', 'require', '评分不能为空'],
            ['evaluate', 'require', '评论不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        if ($param["score"] > 5) $this->error("请检查评分");
        $list = Washlog::get($this->request->param("id"));
        if (empty($list)) $this->error("洗车记录不存在");
        if ($list["status"] == 1) $this->error("该洗车记录已评论");
        $list->save([
            "score" => $param["score"],
            "status" => '1',
            "evaluate" => $param["evaluate"],
            "evaluate_images" => $param["evaluate_images"] ?? "",
            "evaluate_time" => time(),
            "anonymous" => $param["anonymous"] ?? 0,
        ]);

        $this->success("评论成功");
    }

    /**
     * 查核销码
     * */
    public function getCode()
    {
        if (!$this->request->param("id")) $this->error("订单id为空");
        $type = $this->request->param("type") ?? 0;
        $score = $this->request->param("score") ?? 1;
        $where = ["order_id" => $this->request->param("id"), "type_data" => $this->request->param("type")];
        if ($score == 2) {
            $where = [];
            $where["id"] = $this->request->param("id");
        }
        if (empty($type) && $score == 1) {
            $list = Order::field("id,code,write_number")->where(["id" => $this->request->param("id")])->find();
        }
        if (!empty($type) || $score == 2) {
            $list = Mycard::field("id,code,from_unixtime(start_time, '%Y-%m-%d %H:%i:%s') start_time,
        from_unixtime(end_time, '%Y-%m-%d %H:%i:%s') end_time,write_number")
                ->where($where)
                ->find();
            if (!empty($list)) {
                $list["writelog"] = Mycardlog::field("write_number")->where(["mycard_id" => $list["id"]])->where("residue > 0")->select();
            }
        }
        $this->success("成功", $list);
    }
}
